#!/usr/bin/env python
# browsershots.org ShotServer 0.3-beta1
# Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston,
# MA 02111-1307, USA.

"""
Resize a number of screenshot images. Will create an output folder for
new width if necessary. Please make sure that the web server has read
and write permissions on the new files. Usage:
# resize.py <width> <filenames...>
"""

__revision__ = '$Rev: 1326 $'
__date__ = '$Date: 2007-05-28 16:05:19 +0000 (Mon, 28 May 2007) $'
__author__ = '$Author: johann $'

import sys
import os


def zoom(filename, width):
    """
    Scale the PNG image given by the filename parameter to a new width.
    Save it with the same filename in a folder whose name is the new width.
    Skip existing files.
    """
    dest = "%d/%s" % (width, os.path.basename(filename))
    if os.path.isfile(dest):
        return

    command = "pngtopnm %s" % filename
    command += " | pnmscale -width %d" % width
    command += " | pnmtopng"
    command += " > %s" % dest
    print command
    result = os.system(command)
    if result:
        raise RuntimeError("failed with exit code %d" % result)


output_width = int(sys.argv[1])
if not os.path.isdir(str(output_width)):
    os.mkdir(str(output_width))
for input_filename in sys.argv[2:]:
    zoom(input_filename, output_width)
